package com.dinggou.shopjb.view;

import static com.dinggou.shopjb.utils.RouteUtil.gotoActivity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dinggou.shopjb.R;
import com.dinggou.shopjb.activitys.BuyAgreementActivity;
import com.dinggou.shopjb.activitys.MainActivity;
import com.dinggou.shopjb.adapters.OrderTypeRVAdapter;
import com.dinggou.shopjb.application.MyApplication;
import com.dinggou.shopjb.base.BaseActivity;
import com.dinggou.shopjb.base.BaseRVAdapter;
import com.dinggou.shopjb.bean.CreateOrderResultBean;
import com.dinggou.shopjb.bean.OrderInfoBean;
import com.dinggou.shopjb.bean.UserInfoBean;
import com.dinggou.shopjb.bean.UserTicketBean;
import com.dinggou.shopjb.core.AppAction;
import com.dinggou.shopjb.net.ActionCallbackListener;
import com.dinggou.shopjb.utils.DataUtils;
import com.dinggou.shopjb.utils.GlideUtils;
import com.dinggou.shopjb.utils.RouteUtil;
import com.dinggou.shopjb.utils.ToastUtil;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.model.GoodsItemBean;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class OrderCreateDialog extends MyDialog implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, AmountGroup.AmountGroupListener {
    private View rootView;
    private Context mContext;
    private RecyclerView rv_type;
    private TextView tv_pro_name;
    private TextView tv_available_amount;
    private TextView tv_goods_agreement;
    private CustomTextView tv_now_price;
    private CustomTextView tv_prod_change_value;
    private CustomTextView tv_prod_change_proportion;
    private TextView tv_service, tv_total_p;
    private TextView tv_order_price;
    private TextView tv_recharge;
    private TextView tv_ticket;
    private TextView tv_price_unit;
    private RelativeLayout ll_buy_up;
    private RelativeLayout ll_buy_down;
    private TextView tv_choose_money_desc;
    private TextView tv_buy_up;
    private TextView tv_buy_down;
    private TextView tv_buy_down_percent, tv_buy_up_percent;
    private ImageView iv_up, iv_down, iv_goods_img, iv_close;
    private View view_top;
    private AmountGroup mAmountGroup;
    private RadioButton rb_balance;
    private RadioButton rb_ticket;
    private Button btn_submit;
    private TextView tv_integral;
    private TextView tv_experience;
    private TextView tv_get_integral;
    private RedSeekBar sbr_up;
    private GreenSeekBar sbr_down;
    private TextView tv_label_01, tv_label_02, tv_label_03;

    private int mTradeType;//购买类型
    private UserInfoBean mAccountBean;//用户信息
    private GoodsAllBean mGroup;//合约
    private List<GoodsItemBean> mList;//商品列表
    private GoodsItemBean mProInfoItemBean;//当前商品
    private CreateOrderDialogListener mListener;
    private Map<String, Integer> ticketMap = new HashMap<>();//优惠券
    private int mOrderAmount = 1;
    private double mSingleProfit = 1;
    private int ticketCount;
    private AppAction mAppAction;
    private OrderTypeRVAdapter mTypeAdapter;
    private String mFollowId;//跟单id
    private String mFollowUserId;//跟单用户id
    private int mIsFirst;//0老用户 1新用户
    private double unitPrice;//单价
    private int mChoosePosition;

    public OrderCreateDialog(Context context, boolean isCancelAble, int gravity) {
        super(context, isCancelAble, gravity);
        this.mContext = context;
        Window w = this.getWindow();
        if (w != null) {
            w.setWindowAnimations(R.style.dialogTranslateAnim);
        }
        rootView = LayoutInflater.from(context).inflate(R.layout.dialog_create_order, null);
        setContentView(rootView);
        findViews(rootView);
        mAppAction = ((MyApplication) mContext.getApplicationContext()).getAppAction();
    }

    private void findViews(View view) {
        view_top = view.findViewById(R.id.view_top);
        iv_close = view.findViewById(R.id.iv_close);
        iv_goods_img = view.findViewById(R.id.iv_goods_img);
        tv_pro_name = view.findViewById(R.id.tv_pro_name);
        tv_now_price = view.findViewById(R.id.tv_now_price);
        tv_prod_change_value = view.findViewById(R.id.tv_prod_change_value);
        tv_prod_change_proportion = view.findViewById(R.id.tv_prod_change_proportion);
        ll_buy_up = view.findViewById(R.id.ll_buy_up);
        tv_label_01 = view.findViewById(R.id.tv_label_01);
        tv_label_02 = view.findViewById(R.id.tv_label_02);
        tv_label_03 = view.findViewById(R.id.tv_label_03);
        iv_up = view.findViewById(R.id.iv_up);
        iv_down = view.findViewById(R.id.iv_down);
        tv_available_amount = view.findViewById(R.id.tv_available_amount);
        tv_goods_agreement = view.findViewById(R.id.tv_goods_agreement);
        tv_order_price = view.findViewById(R.id.tv_order_price);
        tv_service = view.findViewById(R.id.tv_service);
        tv_total_p = view.findViewById(R.id.tv_total_p);
        tv_recharge = view.findViewById(R.id.tv_recharge);
        tv_ticket = view.findViewById(R.id.tv_ticket);
        tv_price_unit = view.findViewById(R.id.tv_price_unit);
        mAmountGroup = (AmountGroup) view.findViewById(R.id.amount_group);
        rb_ticket = (RadioButton) view.findViewById(R.id.rb_ticket);
        rb_balance = (RadioButton) view.findViewById(R.id.rb_balance);
        btn_submit = (Button) view.findViewById(R.id.btn_submit);
        sbr_up = (RedSeekBar) view.findViewById(R.id.sbr_up);
        sbr_down = (GreenSeekBar) view.findViewById(R.id.sbr_down);
        rv_type = view.findViewById(R.id.rv_type);
        ll_buy_down = view.findViewById(R.id.ll_buy_down);
        tv_buy_up = view.findViewById(R.id.tv_buy_up);
        tv_buy_down = view.findViewById(R.id.tv_buy_down);
        tv_integral = view.findViewById(R.id.tv_integral);
        tv_experience = view.findViewById(R.id.tv_experience);
        tv_get_integral = view.findViewById(R.id.tv_get_integral);
        tv_choose_money_desc = view.findViewById(R.id.tv_choose_money_desc);
        tv_buy_up_percent = view.findViewById(R.id.tv_buy_up_percent);
        tv_buy_down_percent = view.findViewById(R.id.tv_buy_down_percent);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);
        rv_type.setLayoutManager(gridLayoutManager);

        btn_submit.setOnClickListener(this);
        tv_recharge.setOnClickListener(this);
        rb_ticket.setOnCheckedChangeListener(this);
        rb_balance.setOnCheckedChangeListener(this);
        view_top.setOnClickListener(this);
        mAmountGroup.setAmountGroupListener(this);
        ll_buy_up.setOnClickListener(this);
        ll_buy_down.setOnClickListener(this);
        tv_get_integral.setOnClickListener(this);
        iv_close.setOnClickListener(this);
        tv_goods_agreement.setOnClickListener(this);
    }

    private void routeAgreement() {
        String mobile = DataUtils.getMobile(mContext);
        String url = "";
        String model;
        if (mTradeType == 2) {
            model = "现价订购";
        } else {
            model = "计算价订购";
        }
        String orderMoney =  rb_ticket.isChecked() ? "0" : ArithUtil.mul(mProInfoItemBean.unit_price, mOrderAmount)+"";
        Bundle bundle = new Bundle();
        bundle.putString("product", mProInfoItemBean.pro_name);//商品名
        bundle.putString("code", mProInfoItemBean.product_code );//商品代码
        bundle.putString("count", mOrderAmount+"");//份数
        bundle.putString("model", model);//模式
        bundle.putString("price", orderMoney);//定金
        bundle.putString("order", "以实际下单数据为准");//订单号
        bundle.putString("fee",  ArithUtil.mul(mOrderAmount, mProInfoItemBean.trade_fee)+"");//服务费
        gotoActivity(mContext, BuyAgreementActivity.class, bundle);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_goods_agreement:
                routeAgreement();
                break;
            case R.id.tv_recharge:
                //去充值
                RouteUtil.toRechargeActivity((BaseActivity) mContext);
                break;
            case R.id.btn_submit:
                createOrder();
                break;
            case R.id.ll_buy_up:
                setBuyTrade(2);
                break;
            case R.id.ll_buy_down:
                setBuyTrade(1);
                break;
            case R.id.iv_close:
            case R.id.view_top:
                dismiss();
                break;
            case R.id.tv_get_integral:
                RouteUtil.toMainActivity((BaseActivity) mContext, MainActivity.TAB_WELFATE);
                dismiss();
                break;
        }
    }

    public void setCreateOrderDialogListener(CreateOrderDialogListener listener) {
        this.mListener = listener;
    }

    public void setChoosePosition(int position) {
        this.mChoosePosition = position;
    }

    public void init(GoodsAllBean group, UserInfoBean account, int tradeType) {
        this.mGroup = group;
        this.mTradeType = tradeType;
        this.mAccountBean = account;
        mList = mGroup.goods_list;
        DataUtils.setUserLevel(mContext, account.level);

        //设置商品列表
        mTypeAdapter = new OrderTypeRVAdapter(mContext, mList);
        mTypeAdapter.setType(mTradeType);
        rv_type.setAdapter(mTypeAdapter);
        mTypeAdapter.setOnItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(List data, View view, int position, long id) {
                mTypeAdapter.setPosition(position);
                refreshGoodsInfo(position);
            }
        });

        //初始化商品列表
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).unit_price == unitPrice) {
                mTypeAdapter.setPosition(i);
                refreshGoodsInfo(i);
            }
        }

        //设置其他数据
        setPrice();
        setSeekBarMaxMinValue();
        tv_label_01.setText("原料最新价(元/" + mGroup.unit + ")");
        tv_available_amount.setText(mAccountBean.availablebalance + "元");
        setTicketInfo(account);
        if (mTradeType == 2) {
            setBuyTrade(2);
        } else {
            setBuyTrade(1);
        }

        mAmountGroup.init();
    }

    /**
     * 设置价格
     */
    private void setPrice() {
        double changeValue = ArithUtil.sub(mGroup.latest_price, mGroup.price_end_lastday);
        double changeProportion = 0;
        int buyUpPeople = 0;
        if (mGroup.price_end_lastday != 0) {
            changeProportion = ArithUtil.div(ArithUtil.mul(changeValue, 100), mGroup.price_end_lastday, 2);
        }
        if (changeValue >= 0) {
            int redColor = ContextCompat.getColor(mContext, R.color.buy_red);
            tv_now_price.setTextColor(redColor);
            tv_prod_change_value.setTextColor(redColor);
            tv_prod_change_proportion.setTextColor(redColor);
            buyUpPeople = 55 + new Random().nextInt(11);

            tv_prod_change_value.setText("+" + ArithUtil.format(changeValue));
            tv_prod_change_proportion.setText("+" + changeProportion + "%");
        } else {
            int greenColor = ContextCompat.getColor(mContext, R.color.buy_green);
            tv_now_price.setTextColor(greenColor);
            tv_prod_change_value.setTextColor(greenColor);
            tv_prod_change_proportion.setTextColor(greenColor);
            buyUpPeople = 45 - new Random().nextInt(11);

            tv_prod_change_value.setText(ArithUtil.format(changeValue) + "");
            tv_prod_change_proportion.setText(changeProportion + "%");
        }
        tv_now_price.setText(mGroup.latest_price + "");
        tv_buy_up_percent.setText(buyUpPeople + "%用户订购");
        tv_buy_down_percent.setText(100 - buyUpPeople + "%用户订购");
    }

    /**
     * 刷新商品
     *
     * @param currentIndex
     */
    private void refreshGoodsInfo(int currentIndex) {
        mProInfoItemBean = mList.get(currentIndex);

        GlideUtils.showImageRoundOptions(mContext, mProInfoItemBean.product_img, iv_goods_img, 12);
        tv_pro_name.setText(mProInfoItemBean.pro_name);
        tv_choose_money_desc.setText("原料价格每波动" + FormatUtil.formatDouble2(ArithUtil.div(1, mGroup.multiple)) + "点损益" + mProInfoItemBean.k_amount + "元");

        setSeekBarMaxMinValue();

        Integer ticket = ticketMap.get(mProInfoItemBean.goods_id);
        ticketCount = ticket == null ? 0 : ticket;
        tv_ticket.setText(ticketCount + "张");

        mSingleProfit = mProInfoItemBean.k_amount;
        calculateOrderPrice();
    }

    /**
     * 计算订单价格
     */
    private void calculateOrderPrice() {
        double service;
        String orderPrice;
        String unitText;
        String serviceText;
        if (rb_ticket.isChecked()) {
            unitText = "张代金券";
            orderPrice = "0";
            serviceText = "元(含退订服务费:0元)";

            tv_integral.setText("0积分");
            tv_experience.setText("0经验值");
        } else {
            unitText = "元";
            service = ArithUtil.mul(mOrderAmount, mProInfoItemBean.trade_fee);
            orderPrice = ArithUtil.mul(mProInfoItemBean.unit_price, mOrderAmount) + "";
            serviceText = "元（含退订服务费" + FormatUtil.formatDouble2(service) + "元）";

            tv_integral.setText(FormatUtil.formatDouble2(Math.round(ArithUtil.mul(service, 5))) + "积分");
            tv_experience.setText(FormatUtil.formatDouble2(ArithUtil.mul(service, 100)) + "经验值");
        }
        sbr_up.setUnitPrice(mProInfoItemBean.unit_price);
        sbr_down.setUnitPrice(mProInfoItemBean.unit_price);
        sbr_up.setAmount(mOrderAmount);
        sbr_down.setAmount(mOrderAmount);
        sbr_up.setSingleProfit(mSingleProfit);
        sbr_down.setSingleProfit(mSingleProfit);
        sbr_up.calculateProfitAndLoss();
        sbr_down.calculateProfitAndLoss();

        tv_order_price.setText(orderPrice);
        tv_price_unit.setText(unitText);
        tv_service.setText(serviceText);
    }

    /**
     * 设置进度条
     */
    private void setSeekBarMaxMinValue() {
        int maxStop;
        int minStop;
        int maxTarget;
        int minTarget;

        int default_target;
        int default_stop;

        if (rb_ticket.isChecked()) {
            maxTarget = mProInfoItemBean.max_ticket_target_profit;
            minTarget = mProInfoItemBean.min_ticket_target_profit;
            maxStop = mProInfoItemBean.max_ticket_stop_loss;
            minStop = mProInfoItemBean.min_ticket_stop_loss;

            default_target = maxTarget;
            default_stop = maxStop;
        } else {
            maxTarget = mProInfoItemBean.max_target_profit;
            minTarget = mProInfoItemBean.min_target_profit;
            maxStop = mProInfoItemBean.max_stop_loss;
            minStop = mProInfoItemBean.min_stop_loss;

            default_target = mProInfoItemBean.default_target_profit;
            default_stop = mProInfoItemBean.default_stop_loss;
        }

        sbr_up.setMaxMinValue(maxTarget, minTarget, false);
        sbr_down.setMaxMinValue(maxStop, minStop, false);
        sbr_up.setValue(default_target);
        sbr_down.setValue(default_stop);
    }

    /**
     * 设置优惠券
     *
     * @param paramT
     */
    public void setTicketInfo(UserInfoBean paramT) {
        ticketMap.clear();
        List<UserTicketBean> list = paramT.ticket;
        if (list != null) {
            for (UserTicketBean ticket : list) {
                ticketMap.put(ticket.goods_id, ticket.count);
            }
        }
        Integer ticket = ticketMap.get(mProInfoItemBean.goods_id);
        ticketCount = ticket == null ? 0 : ticket;
        tv_ticket.setText(ticketCount + "张");
    }

    private void createOrder() {
        if (rb_ticket.isChecked() && mOrderAmount > 1) {
            ToastUtil.showToast(mContext, "每次只能使用一张代金券");
            return;
        }
        if (rb_ticket.isChecked() && ticketCount < mOrderAmount) {
            ToastUtil.showToast(mContext, "代金券不足");
            return;
        }
        if (Double.parseDouble(tv_order_price.getText().toString()) > mAccountBean.availablebalance){
            ToastUtil.showToast(mContext, "余额不足");
            return;
        }
        mListener.onLoading();
        final OrderInfoBean order = new OrderInfoBean();
        order.goods_id = (mProInfoItemBean.goods_id);
        order.trade_type = (this.mTradeType);
        order.amount = (mOrderAmount);
        order.use_ticket = (rb_ticket.isChecked() ? 1 : 0);
        order.target_profit = (sbr_up.getValue());
        order.stop_loss = (sbr_down.getValue());
        order.isFirst = mIsFirst;
        if (!TextUtils.isEmpty(mFollowId)) {
            order.follow_order_id = mFollowId;
        }
        if (!TextUtils.isEmpty(mFollowUserId)) {
            order.user_id = mFollowUserId;
        }
        mAppAction.createPro(order, new ActionCallbackListener<CreateOrderResultBean>() {
            @Override
            public void onSuccess(CreateOrderResultBean data) {
                mListener.onCancelLoading();
                dismiss();
                if (!isUserLevelUp(data)) {
                    showSuccessDialog(data);
                }
                mListener.onCreateOrderSuccess();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                mListener.onCancelLoading();
                if (message.contains("余额不足")) {
                    showRechargeDialog();
                } else {
                    ToastUtil.showToast(mContext, message);
                }
            }
        });
    }

    private void showRechargeDialog() {
        new PromptDialog.Builder(mContext)
                .setTitle("余额不足")
                .setButton("取消", "去充值")
                .setOnConfirmListener(new PromptDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        RouteUtil.toRechargeActivity((BaseActivity) mContext);
                    }
                })
                .show();
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.rb_ticket:
                if (b) {
                    rb_balance.setChecked(false);
                }
                setSeekBarMaxMinValue();
                break;
            case R.id.rb_balance:
                if (b) {
                    rb_ticket.setChecked(false);
                }
                break;
        }
        calculateOrderPrice();
    }


    private void showSuccessDialog(CreateOrderResultBean bean) {
        OrderSuccessDialog orderSuccessDialog = new OrderSuccessDialog(mContext);
        orderSuccessDialog.init(bean);
        orderSuccessDialog.show();

    }

    private boolean isUserLevelUp(CreateOrderResultBean bean) {
        if (bean == null)
            return false;
        int level = bean.getLevel();
        if (level > 1 && level > DataUtils.getUserLevel(mContext)) {
            UserLevelUpDialog dialog = new UserLevelUpDialog(mContext);
            dialog.init(bean);
            dialog.show();
            DataUtils.setUserLevel(mContext, level);
            return true;
        }
        return false;
    }

    public void setUnitPrice(double unit) {
        this.unitPrice = unit;
    }

    public void setNewPrice() {
//        mGroup.latest_price = price;
        setPrice();
    }

    public String getCode() {
        return mGroup.pro_code;
    }

    /**
     * 设置购买类型及按钮颜色状态
     *
     * @param tradeType
     */
    private void setBuyTrade(int tradeType) {
        this.mTradeType = tradeType;
        this.mTypeAdapter.setType(this.mTradeType);
        if (this.mTradeType == 2) {
            tv_buy_up.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            tv_buy_up_percent.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            ll_buy_up.setBackgroundResource(R.drawable.img_dialog_order_up);
            iv_up.setImageResource(R.drawable.img_dialog_up);

            tv_buy_down.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
            tv_buy_down_percent.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
            ll_buy_down.setBackgroundResource(R.drawable.img_dialog_order_down_normal);
            iv_down.setImageResource(R.drawable.img_dialog_down_dark);
            setBuyType(true);
        } else {
            tv_buy_up.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
            tv_buy_up_percent.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
            ll_buy_up.setBackgroundResource(R.drawable.img_dialog_order_up_normal);
            iv_up.setImageResource(R.drawable.img_dialog_up_dark);

            tv_buy_down.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            tv_buy_down_percent.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            ll_buy_down.setBackgroundResource(R.drawable.img_dialog_order_down);
            iv_down.setImageResource(R.drawable.img_dialog_down);
            setBuyType(false);
        }
    }

    /**
     * 设置按钮颜色
     *
     * @param isUp
     */
    private void setBuyType(boolean isUp) {
        int background;
        if (isUp) {
            background = R.drawable.radio_red_selector;
            btn_submit.setBackgroundResource(R.drawable.border_red_01_solid_dp8);
        } else {
            background = R.drawable.radio_green_selector;
            btn_submit.setBackgroundResource(R.drawable.border_green_buy_solid_dp8);
        }
        mAmountGroup.setBackgroundStyle(background);
    }

    public void setFollowId(String mFollowId) {
        this.mFollowId = mFollowId;
    }

    public void setmFollowUserId(String mFollowUserId) {
        this.mFollowUserId = mFollowUserId;
    }

    public void setmIsFirst(int mIsFirst) {
        this.mIsFirst = mIsFirst;
    }

    @Override
    public void onCheckedAmount(int amount) {
        mOrderAmount = amount;
        calculateOrderPrice();
    }

    public void refreshBalance() {
        tv_available_amount.setText(DataUtils.getAvailableBalance(mContext));
    }

    public interface CreateOrderDialogListener {
        void onDialogLogout();

        void onLoading();

        void onCancelLoading();

        void onCreateOrderSuccess();

        void onDismiss();

        void onShow();
    }
}
